const router = require('koa-router')()
const jwt = require('jsonwebtoken')

const { register, userNameFilter, login } = require('../controller/users')
const { SuccessModel, ErrorModel } = require('../model/resModel')

const { AUTORIZATION } = require('../conf/db')
router.prefix('/api/users')

router.post('/register', async function (ctx, next) {
  const { username, password } = ctx.request.body
  console.log(username, password, '调用')
  console.log(ctx.user)
  // 得有权限
  if (ctx.user && context.user.level == 1) {


    console.log(ctx.user.level)
    if (!username || !password) {
      ctx.body = new ErrorModel('用户名或者密码不能为空')
      return
    }
    const row = await userNameFilter(username)
    if (row) {
      ctx.body = new ErrorModel('用户名已存在')
      return
    }
    const data = await register(username, password)
    if (data) {
      ctx.body = new SuccessModel(data)
      return
    }
    ctx.body = new ErrorModel('注册失败，请检查用户名或密码')
  } else {
    ctx.body = new ErrorModel('暂无权限注册，请联系管理员')
  }
})
// 登录

router.post('/login', async function (ctx, next) {
  const { username, password } = ctx.request.body
  if (!username || !password) {
    ctx.body = new ErrorModel('用户名密或密码不能为空')
    return
  }
  const data = await login(username, password)
  if (data.username) {
    // 生成token
    const token = jwt.sign({
      username: data.username,
      id: data.id,
      level: data.level
    }, AUTORIZATION.jwtSecret, { expiresIn: AUTORIZATION.tokenExpresTime })
    // 设置 session
    // ctx.session
    const userData = {
      token
    }
    ctx.body = new SuccessModel(userData)
    return
  }
  ctx.body = new ErrorModel('登录失败，请检查用户名或者密码')
})

router.get('/', function (ctx, next) {
  ctx.body = 'this is a users response!'
})

router.get('/bar', function (ctx, next) {
  ctx.body = 'this is a users/bar response'
})

module.exports = router
